package com.yutel.gps.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.yutel.gps.model.LocationsNode;
import com.yutel.gps.model.RunParameter;

public class TableDBDao extends OracleDao {

	public TableDBDao() {
	}

	public List<LocationsNode> query() {
		List<LocationsNode> list = new ArrayList<LocationsNode>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String sql = querySql();
		try {
			conn = getConnection();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while (rs.next()) {
				LocationsNode ln = new LocationsNode();
				ln.setSrcLng(rs.getString(1));
				ln.setSrcLat(rs.getString(2));
				ln.setStatus(RunParameter.getIns().getStatusValue());
				list.add(ln);
			}
			return list;
		} catch (SQLException e) {
			log.error(sql, e);
			return list;
		} finally {
			close(conn, stmt, rs);
		}
	}

	public int save(LocationsNode ln) {
		Connection conn = null;
		PreparedStatement stmt = null;
		String sql = saveSql();
		try {
			conn = getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, ln.getAimLng());
			stmt.setString(2, ln.getAimLat());
			stmt.setInt(3, ln.getStatus());
			stmt.setString(4, ln.getSrcLng());
			stmt.setString(5, ln.getSrcLat());
			return stmt.executeUpdate();
		} catch (SQLException e) {
			log.error(sql, e);
			return 0;
		} finally {
			close(conn, stmt, null);
		}
	}

	private String querySql() {
		RunParameter rp = RunParameter.getIns();
		StringBuilder sb = new StringBuilder();
		sb.append("select * from(");
		sb.append("select ").append(rp.getSrcLngColumn());
		sb.append(",").append(rp.getSrcLatColumn());
		sb.append(",rownum as rn");
		sb.append(" from ").append(rp.getTable());
		sb.append(" where ").append(rp.getStatusColumn());
		sb.append("=").append(rp.getStatusValue());
		sb.append(" order by ").append(rp.getSrcLngColumn());
		sb.append(",").append(rp.getSrcLatColumn());
		sb.append(") where rn<100");
		return sb.toString();
	}

	private String saveSql() {
		RunParameter rp = RunParameter.getIns();
		StringBuilder sb = new StringBuilder();
		sb.append("update ").append(rp.getTable());
		sb.append(" set ").append(rp.getAimLngColumn());
		sb.append("=?,").append(rp.getAimLatColumn());
		sb.append("=?,").append(rp.getStatusColumn());
		sb.append("=? where ").append(rp.getSrcLngColumn());
		sb.append("=? and ").append(rp.getSrcLatColumn());
		sb.append("=?");
		return sb.toString();
	}

}
